//
//  EF_WKWebView.m
//  J智现场
//
//  Created by song on 2017/11/13.
//  Copyright © 2017年 王长飞. All rights reserved.
//

#import "GoodsDetailController.h"
#import <WebKit/WebKit.h>
#import "GoodsDetailModel.h"
#import "EFAdView.h"

@interface GoodsDetailController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,BaseModelProtocol>

@property (nonatomic,strong)UIScrollView *scrollView;

@property (nonatomic, strong) UILabel *titlelab;

//iOS8之后苹果推荐使用WKWebView替代UIWebView
@property (nonatomic, strong) WKWebView *webView;

@property(nonatomic,strong)UIProgressView *progressView;
@property(nonatomic,strong)GoodsDetailModel *infoModel;
@property (nonatomic,strong)UIView *bannerBgView ;
@property (nonatomic,strong)UIView *detailBgView;
@property (nonatomic,strong)GoodsDetailData *goodsDetailData;

@end

@implementation GoodsDetailController

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //移除监听
    [self.webView removeObserver:self forKeyPath:@"loading"];
    [self.webView removeObserver:self forKeyPath:@"title"];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)initView
{
    [self.navBarView addTitle:@"商品详情"];
    [super initView];

    [self.view addSubview:self.scrollView];
    self.scrollView.backgroundColor = kColorDefultBg;
    [self.scrollView addSubview:self.bannerBgView];
    [self.infoModel getDataWith:self.productId];
        
}

- (void)getDataFinish:(BaseModel *)baseModel netResponse:(BaseResponse *)response{
    GoodsDetailResponse *resp = (GoodsDetailResponse *)response;
    self.goodsDetailData = resp.resObject;
    [self setUpComponet];
}

- (void)setUpComponet{
    
    [self addBannerViewWith:NULL];
    [self addGoodsInfo];
    [self addSellInfo];
    [self addDetailView];
    [self addServiceRule];
    [self addRefundRule];
    [self creatProgressView];
    //添加KVO监听
    [self.webView addObserver:self
                   forKeyPath:@"loading"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"title"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"estimatedProgress"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
}

- (void)addBannerViewWith:(NSArray *)response
{
    NSMutableArray *urlArray = [NSMutableArray array];
    if([self.goodsDetailData.banner containsString:@","]){
        [urlArray addObjectsFromArray:[self.goodsDetailData.banner componentsSeparatedByString:@","]];
    }else{
        [urlArray addObject:self.goodsDetailData.banner];
    }
    
    [self.bannerBgView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    EFAdView *adView = [EFAdView adScrollViewWithFrame:CGRectMake(0, 0, self.bannerBgView.width, self.bannerBgView.height) modelArray:urlArray imagePropertyName:@"imgurl" titlePropertyName:@"name"];
    [self.bannerBgView addSubview:adView];
}

- (void)addGoodsInfo{
    
    UIView *infoView = [[UIView alloc]initWithFrame:CGRectMake(0, self.bannerBgView.bottom, SCREEN_WIDTH, 80)];
    infoView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:infoView];
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(12, 6, infoView.width-20, 40)];
    titleLab.text = self.goodsDetailData.title;
    titleLab.textColor = kTitleColor_black;
    titleLab.font = [UIFont boldSystemFontOfSize:16];
    [infoView addSubview:titleLab];
    
    UILabel *promotionPriceLab = [[UILabel alloc] initWithFrame:CGRectMake(12, titleLab.bottom,42, 30)];
    promotionPriceLab.text = [NSString stringWithFormat:@"¥%@",self.goodsDetailData.promotionPrice];
    promotionPriceLab.textColor = [UIColor redColor];
    promotionPriceLab.font = [UIFont systemFontOfSize:12];
    [infoView addSubview:promotionPriceLab];
    
    float width = [PublicUtils getLabelWidthWithString:promotionPriceLab.text font:promotionPriceLab.font];
    UILabel *originalPriceLab = [[UILabel alloc] initWithFrame:CGRectMake(width+23, titleLab.bottom, 200, 30)];
//    originalPriceLab.text = self.goodsDetailData.originalPrice;
    originalPriceLab.font = [UIFont systemFontOfSize:12];
    originalPriceLab.textColor = kTitleColor_light;
    [infoView addSubview:originalPriceLab];
    
    NSString *originalPrice = self.goodsDetailData.originalPrice;
    NSUInteger length = [originalPrice length];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:originalPrice];
   [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
   [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, length)];
    [originalPriceLab setAttributedText:attri];

}

- (void)addSellInfo{
    UIView *sellView = [[UIView alloc]initWithFrame:CGRectMake(0, self.bannerBgView.bottom+80, SCREEN_WIDTH, 30)];
    sellView.backgroundColor = kColorDefultBg;
    [self.scrollView addSubview:sellView];
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10,7 , 16, 16)];
    imageView.image = kImage(@"yunfei");
    [sellView addSubview:imageView];
    
    UILabel *sellLab = [[UILabel alloc] initWithFrame:CGRectMake(imageView.right+5, 0, 100, sellView.height)];
    sellLab.textColor = kTitleColor_midden;
    sellLab.font = KFontSmall;
    [sellView addSubview:sellLab];
    
    NSString *whopayLogistics = [NSString stringWithFormat:@"%@",self.goodsDetailData.whopayLogistics];
    if(ISEqual(whopayLogistics, @"0")){
        sellLab.text = @"卖家承担";
    }else{
        sellLab.text = [NSString stringWithFormat:@"运费：¥%@",self.goodsDetailData.logisticsFee];
    }
}

- (void)addDetailView{
    
    UIView *detailBgView = [[UIView alloc]initWithFrame:CGRectMake(0, self.bannerBgView.bottom+80+30, SCREEN_WIDTH, 220)];
    _detailBgView = detailBgView;
    detailBgView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:detailBgView];
    
    UIView *leftLine = [[UIView alloc]initWithFrame:CGRectMake(12, 18, 2, 15)];
    [leftLine setCornerRedius:1];
    leftLine.backgroundColor = UIColorFromRGB1(0x4B8CF1);
    [detailBgView addSubview:leftLine];
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(20, 15, 100, 20)];
    titleLab.text = @"商品详情";
    titleLab.textColor = kTitleColor_midden;
    titleLab.font = kFontMidden;
    [detailBgView addSubview:titleLab];
    
    WKWebViewConfiguration *config = [WKWebViewConfiguration new];
    //初始化偏好设置属性：preferences
    config.preferences = [WKPreferences new];
    //The minimum font size in points default is 0;
    config.preferences.minimumFontSize = 10;
    //是否支持JavaScript
    config.preferences.javaScriptEnabled = YES;
    //不通过用户交互，是否可以打开窗口
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    //通过JS与webView内容交互
    config.userContentController = [WKUserContentController new];
    // 注入JS对象名称senderModel，当JS通过senderModel来调用时，我们可以在WKScriptMessageHandler代理中接收到
    [config.userContentController addScriptMessageHandler:self name:@"senderModel"];
    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(15, 50, SCREEN_WIDTH-30, detailBgView.height-50) configuration:config];
    self.webView.backgroundColor = [UIColor whiteColor];
    [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
//    if (!ISEMPTY(self.htmlString)) {
    [self.webView loadHTMLString:self.goodsDetailData.desc baseURL:nil];
//    }
//    else{
//        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
//    }
    [detailBgView addSubview:self.webView];
    
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
}

#pragma mark - KVO监听函数
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"title"]) {
        self.title = self.webView.title;
    }else if([keyPath isEqualToString:@"loading"]){
        NSLog(@"loading");
    }
    else if ([keyPath isEqualToString:@"estimatedProgress"]){
        //estimatedProgress取值范围是0-1;
        self.progressView.progress = self.webView.estimatedProgress;
    }
    
    if (!self.webView.loading) {
        [UIView animateWithDuration:0.5 animations:^{
            self.progressView.alpha = 0;
        }];
    }
    
    //更具内容的高重置webView视图的高度
    NSLog(@"Height is changed! new=%@", [change valueForKey:NSKeyValueChangeNewKey]);
    NSLog(@"tianxia :%@",NSStringFromCGSize(self.webView.scrollView.contentSize));
    CGFloat newHeight = self.webView.scrollView.contentSize.height;
    NSLog(@"height=====%f",newHeight);
    
}

#pragma mark  - KVO回调
//-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
//
//    //更具内容的高重置webView视图的高度
//    NSLog(@"Height is changed! new=%@", [change valueForKey:NSKeyValueChangeNewKey]);
//    NSLog(@"tianxia :%@",NSStringFromCGSize(self.webView.scrollView.contentSize));
//    CGFloat newHeight = self.webView.scrollView.contentSize.height;
//    NSLog(@"height=====%f",newHeight);
//}

- (void)addServiceRule{
    
    UIView *ruleView = [[UIView alloc]initWithFrame:CGRectMake(0, _detailBgView.bottom+10, SCREEN_WIDTH, 100)];
    ruleView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:ruleView];
    
    UILabel *tagLab = [[UILabel alloc] initWithFrame:CGRectMake(-15, 15, 140, 24)];
    tagLab.text = @"服务规则";
    tagLab.textColor = kTitleColor_midden;
    tagLab.font = [UIFont systemFontOfSize:14];
    tagLab.backgroundColor = UIColorFromRGB1(0xE5B580);
    [tagLab setCornerRedius:12];
    tagLab.textAlignment = NSTextAlignmentCenter;
    [ruleView addSubview:tagLab];
    
    UILabel *textLab = [[UILabel alloc] initWithFrame:CGRectMake(15, tagLab.bottom, SCREEN_WIDTH-20, 60)];
    textLab.text = self.goodsDetailData.refundRuleServices;
    textLab.numberOfLines = 0;
    textLab.textColor = kTitleColor_light;
    textLab.font = KFontSmall;
    [ruleView addSubview:textLab];
}

- (void)addRefundRule{
    
    UIView *ruleView = [[UIView alloc]initWithFrame:CGRectMake(0, _detailBgView.bottom+10+100+10, SCREEN_WIDTH, 80)];
    ruleView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:ruleView];
    
    UILabel *tagLab = [[UILabel alloc] initWithFrame:CGRectMake(-15, 15, 140, 24)];
    tagLab.text = @"退款退货规则";
    tagLab.textColor = kTitleColor_midden;
    tagLab.font = [UIFont systemFontOfSize:14];
    tagLab.backgroundColor = UIColorFromRGB1(0xE5B580);
    [tagLab setCornerRedius:12];
    tagLab.textAlignment = NSTextAlignmentCenter;
    [ruleView addSubview:tagLab];
    
    UILabel *textLab = [[UILabel alloc] initWithFrame:CGRectMake(15, tagLab.bottom, SCREEN_WIDTH-20, 32)];
    textLab.text = self.goodsDetailData.refundRules;
    textLab.textColor = kTitleColor_light;
    textLab.font = KFontSmall;
    [ruleView addSubview:textLab];
}

- (void)goback{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        NSLog(@"back");
    }
}
-(void)gofarward{
    if ([self.webView canGoForward]) {
        [self.webView goForward];
    }
}

-(void)creatProgressView{
    self.progressView = [[UIProgressView alloc]initWithFrame:self.view.bounds];
//    self.progressView.backgroundColor = [UIColor redColor];
    [self.scrollView addSubview:self.progressView];
}


#pragma mark - WKScriptMessageHandler
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    //这里可以通过name处理多组交互
    if ([message.name isEqualToString:@"senderModel"]) {
        //body只支持NSNumber, NSString, NSDate, NSArray,NSDictionary 和 NSNull类型
        NSLog(@"%@",message.body);
    }
    
}

#pragma mark = WKNavigationDelegate
//在发送请求之前，决定是否跳转
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString *hostname = navigationAction.request.URL.host.lowercaseString;
    NSLog(@"%@",hostname);
    if (navigationAction.navigationType == WKNavigationTypeLinkActivated
        && ![hostname containsString:@".baidu.com"]) {
        // 对于跨域，需要手动跳转
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        
        // 不允许web内跳转
        decisionHandler(WKNavigationActionPolicyCancel);
    } else {
        self.progressView.alpha = 1.0;
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    
    
}
//在响应完成时，调用的方法。如果设置为不允许响应，web内容就不会传过来

-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    decisionHandler(WKNavigationResponsePolicyAllow);
}
//接收到服务器跳转请求之后调用
-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}

//开始加载时调用
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
//当内容开始返回时调用
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
//页面加载完成之后调用
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"title:%@",webView.title);
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    
}

#pragma mark WKUIDelegate

//alert 警告框
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"调用alert提示框" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    NSLog(@"alert message:%@",message);
    
}

//confirm 确认框
-(void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认框" message:@"调用confirm提示框" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
    
    NSLog(@"confirm message:%@", message);
    
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"输入框" message:@"调用输入框" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor blackColor];
    }];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler([[alert.textFields lastObject] text]);
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
}

- (UIScrollView *)scrollView{
    
    if (nil == _scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, KNavFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT_EXCEPTNAV)];
        _scrollView.delegate = self ;
        _scrollView.backgroundColor = [UIColor whiteColor];
        _scrollView.contentSize = CGSizeMake(0, SCREEN_HEIGHT+120);
        _scrollView.alwaysBounceVertical = YES ;
    }
    return _scrollView;
}

- (UIView *)bannerBgView
{
    if (nil == _bannerBgView) {
        _bannerBgView = [[UIView alloc]initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-20, 160)];
        _bannerBgView.userInteractionEnabled = YES ;
    }
    return _bannerBgView ;
}

- (GoodsDetailModel *)infoModel{
    
    if (nil == _infoModel) {
        _infoModel = [[GoodsDetailModel alloc]initWithDelegate:self cache:NO];
    }
    return _infoModel;
}

@end
